using System.Collections;

using LocalBoard.Domain;
using LocalBoard.Controller;

namespace LocalBoard.Web.UserControls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	/// <summary>
	///		Summary description for ClubListView.
	/// </summary>
	public partial class ClubListView : System.Web.UI.UserControl
	{
		private object _dataSource = null;
		public object DataSource
		{
			get {return _dataSource;}
			set
			{
				_dataSource = value;
				clubList.DataSource = _dataSource;
				DataBind();
			}
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			if(_dataSource == null)
				clubList.DataSource = new AdminController(Global.AccessorFactory).GetAllClubList();
			DataBind();
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.clubList.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.clubList_ItemDataBound);

		}
		#endregion

		private void clubList_ItemDataBound(object source, RepeaterItemEventArgs e)
		{
			if(e.Item != null && e.Item.DataItem != null
				&& (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
				)
			{
				Club currentClub = e.Item.DataItem as Club;
				HyperLink clubLink = e.Item.FindControl("clubLink") as HyperLink;
				rssLinkControl clubRssLink = e.Item.FindControl("clubRssLink") as rssLinkControl;
				NewMessageIndicator newIndicatorForum = e.Item.FindControl("newIndicatorForum") as NewMessageIndicator;
				Label clubDescription = e.Item.FindControl("clubDescription") as Label;

				clubLink.NavigateUrl = ClubPage.AddClubQueryStringToUrl(clubLink.NavigateUrl, currentClub.Id);
				clubLink.Text = currentClub.Name;
				clubRssLink.ClubId = currentClub.Id;
				ClubController clubController = new ClubController(currentClub.Id, Global.AccessorFactory);
				Message firstMessage = GetFirstMessageFromClub(clubController);
				if(firstMessage != null)
					newIndicatorForum.PostedDate = firstMessage.Date;
				clubDescription.Text = currentClub.Description;
			}
		}

		private Message GetFirstMessageFromClub(ClubController clubController)
		{
			ClubBoardController boardController = new ClubBoardController(clubController, 0, Global.AccessorFactory);
			ArrayList messageList = boardController.GetMessageListForCurrentPage();
			Message firstMessage = null;
			if(messageList.Count > 0)
			{
				firstMessage = messageList[0] as Message;
			}
			return firstMessage;
		}
	}
}
